package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/user/linux-command/client"
	"github.com/user/linux-command/database"
	"github.com/user/linux-command/forwarder"
	"github.com/user/linux-command/models"
)

func main() {
	// 初始化数据库
	if err := database.InitDB(); err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}

	// 创建Gin路由器
	router := gin.Default()

	// 注册路由
	router.POST("/jsonrpc", handleJSONRPC)
	router.POST("/register", handleServiceRegistration)
	router.GET("/health", handleHealthCheck)
	router.GET("/services", handleListServices)

	// 启动服务器
	log.Println("MCP Forwarder Server starting on :8080")
	if err := router.Run(":8080"); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

// handleJSONRPC 处理JSON-RPC请求
func handleJSONRPC(c *gin.Context) {
	var rpcRequest models.JSONRPCRequest
	
	if err := c.ShouldBindJSON(&rpcRequest); err != nil {
		c.JSON(http.StatusBadRequest, models.JSONRPCResponse{
			JSONRPC: "2.0",
			Error: &models.RPCError{
				Code:    -32700,
				Message: "Parse error",
			},
			ID: nil,
		})
		return
	}

	// 验证JSON-RPC版本
	if rpcRequest.JSONRPC != "2.0" {
		c.JSON(http.StatusBadRequest, models.JSONRPCResponse{
			JSONRPC: "2.0",
			Error: &models.RPCError{
				Code:    -32600,
				Message: "Invalid Request",
			},
			ID: rpcRequest.ID,
		})
		return
	}

	// 创建转发器
	fwd := forwarder.NewForwarder()

	// 特殊处理tools/list请求
	if rpcRequest.Method == "tools/list" {
		response := fwd.HandleToolsList(rpcRequest.ID)
		c.JSON(http.StatusOK, response)
		return
	}

	// 转发其他请求
	response, err := fwd.ForwardRequest(&rpcRequest)
	if err != nil {
		c.JSON(http.StatusInternalServerError, models.JSONRPCResponse{
			JSONRPC: "2.0",
			Error: &models.RPCError{
				Code:    -32603,
				Message: "Internal error",
			},
			ID: rpcRequest.ID,
		})
		return
	}

	c.JSON(http.StatusOK, response)
}

// handleServiceRegistration 处理服务注册
func handleServiceRegistration(c *gin.Context) {
	var registrationRequest struct {
		Name        string `json:"name" binding:"required"`
		URL         string `json:"url" binding:"required"`
		Description string `json:"description"`
	}

	if err := c.ShouldBindJSON(&registrationRequest); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Invalid request body",
		})
		return
	}

	// 注册服务
	if err := client.RegisterService(
		registrationRequest.Name,
		registrationRequest.URL,
		registrationRequest.Description,
	); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": fmt.Sprintf("Failed to register service: %v", err),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "Service registered successfully",
		"service": registrationRequest.Name,
	})
}

// handleHealthCheck 健康检查
func handleHealthCheck(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"status":    "healthy",
		"timestamp": "2024-01-01T00:00:00Z",
	})
}

// handleListServices 列出所有已注册的服务
func handleListServices(c *gin.Context) {
	services, err := database.GetAllServices()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to get services",
		})
		return
	}

	var serviceInfos []gin.H
	for _, service := range services {
		tools, err := database.GetToolsByService(service.ID)
		if err != nil {
			tools = []models.MCPTool{}
		}

		serviceInfos = append(serviceInfos, gin.H{
			"id":          service.ID,
			"name":        service.Name,
			"url":         service.URL,
			"description": service.Description,
			"tool_count":  len(tools),
			"is_active":   service.IsActive,
			"created_at":  service.CreatedAt,
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"services": serviceInfos,
		"count":    len(serviceInfos),
	})
}